
package com.bxd.baodan.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.app.Constant;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.fragment.BaseFragment;
import com.bxd.baodan.fragment.LoginFragment;
import com.bxd.baodan.item.UserItem;
import com.bxd.baodan.util.AppManager;
import com.bxd.baodan.util.DensityUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.LoginIMUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.ResourcesUtil;
import com.bxd.baodan.util.SaveMsgUtil;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class LoginActivity extends BaseActivity implements OnClickListener,
        OnPageChangeListener {

    private ViewPager pager;
    private List<BaseFragment> tabs = new ArrayList<BaseFragment>();
    private FragmentPagerAdapter mAdapter;
    private TextView[] tabTextView = null;// 指示器对应的三个TEXTVIEW
    private ImageView tabBottomLine = null;// 指示器底部颜色条
    private int tabWidth = 0; // tab宽度
    private static final int USER_ADVISORY = 0;
    private static final int MICRO_READ = 1;
    private int curTabIndex = USER_ADVISORY;// 默认使用第一个
    private ImageView btn_ksqw;

    public static String question;
    public static String content;

    private ProgressDialog pd;

    private static final int FINISH_ACTIVITY = 2000;
    private LinearLayout mLayoutThirdLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.two_tab);

        setActionBarTitle(ResourcesUtil.getStringById(R.string.ab_title_login));
        initHomeBar(5);
        question = getIntent().getStringExtra("question");
        content = getIntent().getStringExtra("content");
        initView();
    }

    private void initView() {
        mLayoutThirdLogin = (LinearLayout) findViewById(R.id.third_login_layout);
        mLayoutThirdLogin.setVisibility(View.VISIBLE);
        findViewById(R.id.wx_login).setOnClickListener(this);
        findViewById(R.id.qq_login).setOnClickListener(this);
        findViewById(R.id.weibo_login).setOnClickListener(this);

        btn_ksqw = (ImageView) findViewById(R.id.btn_ksqw);
        btn_ksqw.setVisibility(View.GONE);
        tabTextView = new TextView[2];
        tabTextView[USER_ADVISORY] = (TextView) findViewById(R.id.tv_tab1);
        tabTextView[MICRO_READ] = (TextView) findViewById(R.id.tv_tab2);
        tabTextView[USER_ADVISORY].setText("密码登录");
        tabTextView[MICRO_READ].setText("验证码登录");

        // 初始化tab标识线
        tabBottomLine = (ImageView) findViewById(R.id.tabBottomLine);
        initBottomLine();
        tabTextView[USER_ADVISORY].setOnClickListener(this);
        tabTextView[MICRO_READ].setOnClickListener(this);
        pager = (ViewPager) findViewById(R.id.viewPager);

        // tabs.add(new NearbyAdviserFragment());
        tabs.add(new LoginFragment(0));
        tabs.add(new LoginFragment(1));
        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return tabs.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                // TODO Auto-generated method stub
                return tabs.get(arg0);
            }
        };
        pager.setAdapter(mAdapter);
        pager.setOnPageChangeListener(this);
        pager.setCurrentItem(USER_ADVISORY);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_tab1:
                if (curTabIndex != USER_ADVISORY) {
//                    tabTextView[USER_ADVISORY].setTextColor(Color
//                            .parseColor("#05c000"));
                    mLayoutThirdLogin.setVisibility(View.VISIBLE);
                    pager.setCurrentItem(USER_ADVISORY);
                }
                break;
            case R.id.tv_tab2:
                if (curTabIndex != MICRO_READ) {
//                    tabTextView[MICRO_READ].setTextColor(Color
//                            .parseColor("#05c000"));
                    mLayoutThirdLogin.setVisibility(View.GONE);
                    pager.setCurrentItem(MICRO_READ);
                }
                break;

            case R.id.wx_login:
                if (pd == null) {
                    pd = new ProgressDialog(LoginActivity.this);
                    pd.setMessage("登录中...");
                }
                pd.show();
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, authListener);
                break;
            case R.id.qq_login:
                if (pd == null) {
                    pd = new ProgressDialog(LoginActivity.this);
                    pd.setMessage("登录中...");
                }
                pd.show();
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.QQ, authListener);
                break;
            case R.id.weibo_login:
                if (pd == null) {
                    pd = new ProgressDialog(LoginActivity.this);
                    pd.setMessage("登录中...");
                }
                pd.show();
                UMShareAPI.get(LoginActivity.this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.SINA, authListener);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FINISH_ACTIVITY) {
            finish();
            return;
        }
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    UMAuthListener authListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {


            String temp = "";
            for (String key : data.keySet()) {
                temp = temp + key + " : " + data.get(key) + "\n";


            }
            LogUtil.e("temp: " + temp);
            String name;
            String iconurl;
            String gender;
            String uid;
            String thirdparty = "";

            name = data.get("name");
            iconurl = data.get("iconurl");
            gender = data.get("gender");
            uid = data.get("uid");


            if (platform.equals(SHARE_MEDIA.QQ)) {
                thirdparty = "qq";
                uid = data.get("uid").trim();
            } else if (platform.equals(SHARE_MEDIA.WEIXIN)) {
                thirdparty = "wechat";
            } else if (platform.equals(SHARE_MEDIA.SINA)) {
                thirdparty = "sina";
            }

            ThirdInfo thirdInfo = new ThirdInfo(thirdparty, name, iconurl, gender, uid);


            cancelDialog();


            thirdLogin(thirdInfo);


        }


        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            cancelDialog();
            showToast("第三方登录失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            cancelDialog();
            showToast("取消登录");
        }
    };

    private void cancelDialog() {
        if (pd != null) {
            pd.cancel();
            pd = null;
        }
    }


    private void thirdLogin(final ThirdInfo info) {
        NetUtil netUtil = new NetUtil(this, JsonApi.THIRD_LOGIN);

        netUtil.setParams("openid", info.uid);
        netUtil.setParams("thirdparty", info.platform);

        netUtil.postRequest("登录中...", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {
                if (JSONUtil.isSuccess(result)) {

                    String isBind = JSONUtil.getData("isbind", JSONUtil.getData(result));


                    if (isBind.equals("0")) {
//绑定页面
                        openActivity(BindPhoneActivity.class,
                                new String[]{"thirdinfo"},
                                new String[]{new Gson().toJson(info)});
                    } else {
                        LoginInfo loginInfo = LoginInfo.getInstance(LoginActivity.this);
                        loginInfo.saveUserInfo(JSONUtil.getData(result),
                                App.getContext());
                        UserItem user = LoginInfo.getInstance(
                                App.getContext()).getUser();

                        SaveMsgUtil.updateLocalInfo(user,
                                App.getContext());// 更新用户的登录资料到本地
                        App.getContext().sendBroadcast(
                                new Intent(Constant.ACTION_SUCCESS_LOGIN));
                        App.getContext().sendBroadcast(
                                new Intent(Constant.ACTION_SUCCESS_UPLOAD_INFOR));


                        loginIM();  //IM登录

                        AppManager.getInstance().finishOtherActivity(MainActivity.class);

                    }
                }
            }
        });
    }

    public void loginIM() {
        LoginIMUtil loginUtil = new LoginIMUtil(AppManager.getInstance().currentActivity());
        loginUtil.initIM();
        loginUtil.setCallback(new LoginIMUtil.Callback() {
            @Override
            public void next() {

            }
        });
        loginUtil.loginIM();
    }


    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageSelected(int arg0) {
        // 左右滑动切换tab页
        changeTabItem(arg0);
        tabs.get(arg0).onSelected();
        if (arg0 == 0) {
            mLayoutThirdLogin.setVisibility(View.VISIBLE);
        } else {
            mLayoutThirdLogin.setVisibility(View.GONE);
        }
    }

    /**
     * 设置标识线
     */
    private void initBottomLine() {
        RelativeLayout.LayoutParams lParams = (RelativeLayout.LayoutParams) tabBottomLine
                .getLayoutParams();
        DisplayMetrics dm = getResources().getDisplayMetrics();
        lParams.width = dm.widthPixels / 6;
//        lParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
        lParams.setMargins(DensityUtil.dip2px(this, 60), 0, 0, 0);

        tabBottomLine.setLayoutParams(lParams);
//        tabWidth = lParams.width;
        tabWidth = dm.widthPixels / 2;
        // tabBottomLine.setVisibility(View.GONE);
    }

    /**
     * 更新tab文字选中状态
     *
     * @param index
     */
    private void updateTabTextStatus(int index) {
        if (index > 2 || index < 0) {
            return;
        }
        for (TextView tv : tabTextView) {
            tv.setTextColor(getResources().getColor(
                    R.color.text_acount_gray));
        }
        tabTextView[index].setTextColor(getResources().getColor(R.color.text_black));
    }


    /**
     * 切换tab选项
     *
     * @param index
     */
    private void changeTabItem(int index) {
        // if(curTabIndex == index){
        // return;
        // }
        Animation animation = new TranslateAnimation(curTabIndex * tabWidth,
                index * tabWidth, 0, 0);
        curTabIndex = index;
        animation.setFillAfter(true);
        animation.setDuration(300);
        tabBottomLine.startAnimation(animation);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                // 动画结束,更新文字选中状态
                updateTabTextStatus(curTabIndex);
            }
        });
    }


    public class ThirdInfo implements Serializable {
        public ThirdInfo(String platform, String name, String iconurl, String gender, String uid) {
            this.name = name;
            this.iconurl = iconurl;
            this.gender = gender;
            this.uid = uid;
            this.platform = platform;
        }

        public String name;
        public String iconurl;
        public String gender;
        public String uid;
        public String platform;

    }


}
